<?php

namespace app\middleware;

use app\Http\Controllers\Admin\Tool;
use Tinywan\Jwt\JwtToken;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
use support\Db as DB;

class AdminAuthUser implements MiddlewareInterface
{
    use Tool;
    public function process(Request $request, callable $next) : Response
    {
        try {
            JwtToken::getUser();
        } catch (\Exception $e) {
            $msg = $e->getMessage();
            if ($msg === "请求未携带authorization信息") {
                return $this->errorWithInfo("认证出错，请先登录后再访问该接口", 400);
            }
            if ($msg === "非法的authorization信息") {
                return $this->errorWithInfo("认证出错，非法的token信息", 401);
            }
            if ($msg === "身份验证会话已过期，请重新登录！") {
                return $this->errorWithInfo($msg, 402);
            }
        }

        $Auth = $request->header("authorization");
        $token = explode(" ", $Auth);
        $token = DB::table("admin_token")->where("access_token", $token[1])->first();
        if (!$token || !$token->status) {
            return $this->errorWithInfo("登录用户已经退出，无法访问指定的接口", 400);
        }
        return $next($request);
    }

}